package com.shallowUniverse.process.context.user;


import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author gs
 * @date create in 2021/1/8 22:18
 */
public class ProcessUserHolder implements ProcessUserService {

    private static final ThreadLocal<SysUser> userThreadLocal = new ThreadLocal<>();

    @Override
    public synchronized SysUser get() {
        synchronized (ProcessUserHolder.class) {
            if (!ObjectUtils.isEmpty(userThreadLocal.get())) {
                synchronized (ProcessUserHolder.class) {
                    return userThreadLocal.get();
                }
            }
        }
        return null;
    }

    @Override
    public void set(SysUser sysUser) {
        synchronized (ProcessUserHolder.class) {
            if (ObjectUtils.isEmpty(userThreadLocal.get())) {
                synchronized (ProcessUserHolder.class) {
                    userThreadLocal.set(sysUser);
                }
            }
        }
    }

    @Override
    public void clear() {
        synchronized (ProcessUserHolder.class) {
            if (!ObjectUtils.isEmpty(userThreadLocal.get())) {
                synchronized (ProcessUserHolder.class) {
                    userThreadLocal.remove();
                }
            }
        }
    }

    @Override
    public Long getUserId() {
        return get().getUserId();
    }

    @Override
    public Long getUserDept() {
        return get().getUserDept();
    }

    @Override
    public String getUsername() {
        return get().getUsername();
    }

    @Override
    public List<Long> getUserRoles() {
        return get().getUserRoles();
    }

    @Override
    public String getUserReamName() {
        return get().getUserRealName();
    }
}
